package by.koleda.benicetobunnies;

import by.koleda.benicetobunnies.manager.CompaniesManager;
import by.koleda.benicetobunnies.service.BarcodeService;
import by.koleda.benicetobunnies.service.CompaniesService;
import by.koleda.benicetobunnies.service.SearchService;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class MainActivity extends Activity {
	
	public static final String TAG = MainActivity.class.getSimpleName();
	public static final String EXTRA_RESULT_MESSAGE = "result";
	public static final String EXTRA_COMPANY_MESSAGE = "company";
	
	
	private BroadcastReceiver mCompaniesServiceReceiver;
	private BroadcastReceiver mBarcodeServiceReceiver;
	private BroadcastReceiver mSearchServiceReceiver;
	
	private ProgressDialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		setContentView(R.layout.activity_main);
		new IntentIntegrator(this).initiateScan();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, intent);
		if (scanResult != null) {
			if (resultCode == RESULT_OK) {
				String contents = intent.getStringExtra("SCAN_RESULT");
				handleResult(contents);
			} else if (resultCode == RESULT_CANCELED) {
				Log.w(TAG, "SCAN RESULT_CANCELED!");
				finish();
			}
		}
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				new IntentIntegrator(this).initiateScan();
			} else if (resultCode == RESULT_CANCELED) {
				Log.w(TAG, "NEW SCAN RESULT_CANCELED!");
				finish();
			}
		}
	}
	
	private void handleResult(final String contents) {
		showProgressDialog(R.string.loading_title, R.string.database_checking, false);
		if (CompaniesManager.checkEntries(this) == false) {
		Intent intent = new Intent(this, CompaniesService.class);
		startService(intent);
		mCompaniesServiceReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(CompaniesService.ACTION_ON_SUCCESS)) {
					hideProgressDialog();
					unregisterReceiver(mCompaniesServiceReceiver);
					stopService(intent);
					startBarcodeService(contents);
				} else if (action.equals(CompaniesService.ACTION_ON_ERROR)) {
					hideProgressDialog();
					stopService(intent);
					Toast.makeText(MainActivity.this, R.string.error_internet, Toast.LENGTH_LONG).show();
					Log.w(TAG, intent.getStringExtra(CompaniesService.EXTRA_KEY_MESSAGE));
					new IntentIntegrator(MainActivity.this).initiateScan();
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(CompaniesService.ACTION_ON_SUCCESS);
		filter.addAction(CompaniesService.ACTION_ON_ERROR);
		registerReceiver(mCompaniesServiceReceiver, filter);
		} else {
			hideProgressDialog();
			startBarcodeService(contents);
		}
	}
	
	private void startBarcodeService(String barcode) {
		showProgressDialog(R.string.loading_title, R.string.barcode_converting, false);
		mBarcodeServiceReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(BarcodeService.ACTION_ON_SUCCESS)) {
					hideProgressDialog();
					String companyName = intent.getStringExtra(BarcodeService.COMPANY_TAG);
					unregisterReceiver(mBarcodeServiceReceiver);
					stopService(intent);
					startSearchService(companyName);
				} else if (action.equals(BarcodeService.ACTION_ON_ERROR)) {
					hideProgressDialog();
					unregisterReceiver(mBarcodeServiceReceiver);
					stopService(intent);
					Log.w(TAG, intent.getStringExtra(BarcodeService.EXTRA_KEY_MESSAGE));
					Toast.makeText(MainActivity.this, R.string.error_internet, Toast.LENGTH_LONG).show();
					new IntentIntegrator(MainActivity.this).initiateScan();
				}
			}
			
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(BarcodeService.ACTION_ON_SUCCESS);
		filter.addAction(BarcodeService.ACTION_ON_ERROR);
		registerReceiver(mBarcodeServiceReceiver, filter);
		Intent intent = new Intent(this, BarcodeService.class);
		intent.putExtra(BarcodeService.BARCODE_TAG, barcode);
		startService(intent);
	}
	
	private void startSearchService(final String companyName) {
		showProgressDialog(R.string.loading_title, R.string.result_searching, false);
		mSearchServiceReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(SearchService.ACTION_ON_SUCCESS)) {
					int result = intent.getIntExtra(SearchService.RESULT_TAG, 0);
					hideProgressDialog();
					unregisterReceiver(mSearchServiceReceiver);
					stopService(intent);
					Intent resultIntent = new Intent(MainActivity.this, ResultActivity.class);
					resultIntent.putExtra(EXTRA_RESULT_MESSAGE, result);
					resultIntent.putExtra(EXTRA_COMPANY_MESSAGE, companyName);
					startActivityForResult(resultIntent, 1);
				} else if (action.equals(SearchService.ACTION_ON_ERROR)) {
					hideProgressDialog();
					unregisterReceiver(mSearchServiceReceiver);
					stopService(intent);
					Log.w(TAG, intent.getStringExtra(SearchService.EXTRA_KEY_MESSAGE));
					Toast.makeText(MainActivity.this, R.string.error_happened, Toast.LENGTH_LONG).show();
					new IntentIntegrator(MainActivity.this).initiateScan();
				}
			}
			
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(SearchService.ACTION_ON_SUCCESS);
		filter.addAction(SearchService.ACTION_ON_ERROR);
		registerReceiver(mSearchServiceReceiver, filter);
		Intent intent = new Intent(this, SearchService.class);
		intent.putExtra(SearchService.COMPANY_TAG, companyName);
		startService(intent);
	}
	
	private void showProgressDialog(int title, int msg, boolean horizontal) {
		CharSequence message = getText(msg);
		mDialog = new ProgressDialog(this);
		mDialog.setTitle(title);
		mDialog.setMessage(message);
		mDialog.setIndeterminate(true);
	    mDialog.setCancelable(false);
	    if (horizontal) {
	    	mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    }
	    mDialog.show();
	}
	
	private void hideProgressDialog() {
		mDialog.dismiss();
	}
	
}